package com.example.test.advice.第一章_java开发中常用的方法和准则.建议16_易变业务使用脚本语言;

import javax.script.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

/**
 * 命令行可使用使用jrunscript工具
 */
public class Client {

    public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodException {
        //获得一个Javascript的执行引擎
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        //建立上下文变量
        Bindings bind = engine.createBindings();
        bind.put("factor",1);
        //绑定上下文，作用域是当前引擎范围
        engine.setBindings(bind, ScriptContext.ENGINE_SCOPE);
        Scanner input = new Scanner(System.in);
        while (input.hasNextInt()){
            int first = input.nextInt();
            int sec = input.nextInt();
            System.out.println("输入参数是："+first+","+sec);
            //执行js代码
            engine.eval(new FileReader("D:/mode.js"));
            //是否可调用方法
            if(engine instanceof Invocable){
                Invocable in = (Invocable) engine;
                //执行js中的函数
                Double result = (Double) in.invokeFunction("formula",first,sec);
                System.out.println("运算结果是："+result.intValue());
            }
        }
    }
}
